<?php

namespace App\Services\Game\Data\Log\Elasticsearch;


use App\Models\Elasticsearch\Log\GameData;
use App\Services\Service;
use App\Services\Traits\DatabaseElasticsearch;

class GameService extends Service
{
    use DatabaseElasticsearch;

    /**
     * 获取游戏日志列表
     * @param $request
     * @return array
     */
    public function getList($request)
    {

        $params = ['body' => ['track_total_hits' => true]];

        // 筛选【时间】
        if ($this->isValidParam($request, 'datetime')) {

            $datetime = $this->getParamArray($request, 'datetime');

            $params['body']['query']['bool']['must'][] = [
                'range' => [
                    'Time' => [
                        'gte' => $datetime[0] * 1000,
                        'lte' => $datetime[1] * 1000
                    ]
                ]
            ];
        }
        // 筛选【搜索】
        if ($this->isValidParam($request, 'keyword')) {

            $keyword = $this->getParam($request, 'keyword');

            $params['body']['query']['bool']['must'][] = [
                'match_phrase' => [
                    'message' => $keyword
                ]
            ];
        }
        //  高亮关键词
        $params['body']['highlight'] = [
            'fields' => [
                'message' => [
                    'number_of_fragments' => 0
                ]
            ]
        ];
        // 查询字段
        $params['body']['_source'] = [
            'includes' => ['message']
        ];

        // 排序分页
        $this->makeOrderParam($request, $params)->makePaginationParam($request, $params);

        // 查询数据
        $results = GameData::search($params);

        // 数据列表
        $datas = $results['hits']['hits'];
        // 数据条数
        $total = $results['hits']['total']['value'];

        return [
            $datas,
            $total
        ];
    }

}
